package com.draven.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.draven.model.order.OrderDTO;
import com.draven.model.product.ProductDTO;
import com.draven.order.entity.Order;
import com.draven.order.feign.ProductFeignClient;
import com.draven.order.mapper.OrderMapper;
import com.draven.order.service.OrderService;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    ProductFeignClient productFeignClient;

    @Override
    @GlobalTransactional(name = "tx-business-service", rollbackFor = Throwable.class)
    public String create(Long id, Integer num) {
        Order order = new Order();
        order.setName("draven");
        order.setPrice(new BigDecimal(100));
        order.setNum(1);
        order.setOrderDesc("订单创建");
        order.setAddress("广东河源紫金");
        order.setPhone("123456789");
        order.setEmail("draven@qq.com");
        order.setRemark("备注");
        orderMapper.insert(order);
        try {
            productFeignClient.updateStock(id, num);
        } catch (Exception e) {
            // 处理异常，例如记录日志或抛出自定义异常
            throw new RuntimeException("更新库存失败，订单未创建", e);
        }
        return "创建订单成功";
    }

    @Override
    public List<Order> getOrderList() {
        return orderMapper.selectAll();
    }

    @Override
    public Order getOrderById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public String updateOrder(Long id, Order order) {
        return "";
    }

    @Override
    public void deleteOrder(Long id) {
        orderMapper.deleteById(id);
    }

    @Override
    public void deleteOrdersBatch(List<Long> ids) {
        // 遍历传入的订单ID列表
        for (Long id : ids) {
            // 调用OrderMapper的deleteById方法，逐个删除订单
            orderMapper.deleteById(id);
        }
    }

    @Override
    public List<ProductDTO> productPage() {
        return productFeignClient.productPage();
    }

    @Override
    public ProductDTO productDetail(Long id) {
        return productFeignClient.getProductDetail(id);
    }
}
